package com.yungu.swift.api.route.v1.driver;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.api.utils.FileUploadUtil;
import com.yungu.swift.api.utils.RandomUtil;
import com.yungu.swift.assets.driver.model.dto.CarDto;
import com.yungu.swift.assets.driver.model.dto.CarModelDto;
import com.yungu.swift.assets.driver.model.dto.DriverCheckDto;
import com.yungu.swift.assets.driver.model.dto.DriverDto;
import com.yungu.swift.assets.driver.service.CarModelService;
import com.yungu.swift.assets.driver.service.CarService;
import com.yungu.swift.assets.driver.service.DriverCheckService;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.autoconfig.redis.RedisCacheService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.common.model.dto.CommonIdentifyDto;
import com.yungu.swift.common.service.CommonSmsService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.DriverConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.system.marketing.model.dto.MarketingInviteLogDto;
import com.yungu.swift.system.marketing.service.MarketingInviteLogService;
import com.yungu.swift.system.sys.model.dto.SysCompanyDto;
import com.yungu.swift.system.sys.model.dto.SysRegionalAgentDto;
import com.yungu.swift.system.sys.service.SysCompanyService;
import com.yungu.swift.system.sys.service.SysRegionalAgentService;
import com.yungu.swift.utils.Base64Utils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import com.yungu.swift.utils.ValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @author Zerrion
 * @description
 * @date 2018/1/24. <br>
 */
@Controller
@RequestMapping(value = "/admin/driver")
@Api(value = "【司机】【注册】", tags = "司机注册相关接口")
public class DriRegisterApi {

    @Reference
    private SysRegionalAgentService sysRegionalAgentService;
    @Reference
    private SysCompanyService sysCompanyService;
    @Reference
    private CommonSmsService commonSmsService;
    @Reference
    private DriverCheckService driverCheckService;
    @Reference
    private DriverService driverService;
    @Reference
    private MarketingInviteLogService marketingInviteLogService;
    @Autowired
    private RedisCacheService redisCacheService;
    @Reference
    private CarService carService;
    @Reference
    private CarModelService carModelService;

    @RequestMapping(value = {"/send"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "发送验证码", response = ResponseData.class, notes = "发送短信验证码接口")
    public ResponseData<Boolean> send(@RequestParam String mobile, @RequestParam String appid) {
        String decryptMobile = RandomUtil.randomDecrypt(mobile);
        if (!ValidateUtils.validateMobile(decryptMobile)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "手机号码格式错误");
        }

        Map<String, Object> map = MapUtils.build();
        map.put("mobile", decryptMobile);
        map.put("appid", appid);
        //检索有效（未离职）司机
        ResponseData<List<DriverDto>> responseData = driverService.getValidDriver(map);
        if (responseData.isSuccess()) {
            return ResponseData.buildSuccessResponse("已经是平台司机了", true);
        }
        return commonSmsService.sendAliIdentify(mobile, appid);
    }

    @RequestMapping(value = {"/login"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResponseData<DriverCheckDto> adminDriLogin(@RequestParam(value = "mobile") String mobile, @RequestParam(value = "code") String code,
                                                      @RequestParam(value = "appid") String appid, @RequestParam(value = "type") Integer type) {

        Map<String, Object> paramMap = MapUtils.build();

        //校验验证码是否存在
        paramMap.put("mobile", mobile);
        paramMap.put("identifyCode", code);
        paramMap.put("status", CommonConstant.IDENTIFY_CODE_STATUS_UNUSED);
        paramMap.put("appid", appid);
        //增加校验3分钟内只能输错5次
        //一个手机号的注册次数
        int registerCount = 1;
        Object object = redisCacheService.get("driverRegisterCount" + mobile);
        if (object != null) {
            registerCount = (int) object;
        }
        if (registerCount > MagicConstant.INT_FIVE) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "3分钟内连续输错5次，请稍后再试！");
        }
        CommonIdentifyDto identify = commonSmsService.get(paramMap).getData();
        if (identify != null) {
            identify.setStatus(CommonConstant.IDENTIFY_CODE_STATUS_USED);
            //更新验证码
            commonSmsService.edit(identify);

            Map<String, Object> map = MapUtils.build();
            map.put("mobile", mobile);
            map.put("appid", appid);
            //检索最新的审核记录，一个手机号可以有多条审核记录，一条审核记录（审核成功的）对应一条司机信息
            ResponseData<List<DriverDto>> responseData = driverService.getValidDriver(map);
            if (responseData.isSuccess() && !CollectionUtils.isEmpty(responseData.getData())) {
                DriverDto driver = responseData.getData().get(0);
                if (driver.getBusinessType().equals(type)) {
                    //是否相同业务类型
                    return ResponseData.buildErrorResponse(2, "", null);
                } else {
                    //返回单业务错误提示
                    return ResponseData.buildErrorResponse(4, "已有归属业务", null);
                }
            }
            //驳回信息
            map.put("type", type);
            ResponseData<DriverCheckDto> checkDtoResponseData = driverCheckService.getLatest(map);
            // 不为空 说明之前已经有申请过 返回false
            if (checkDtoResponseData.isSuccess() && checkDtoResponseData.getData() != null) {
                DriverCheckDto driverCheckDto = checkDtoResponseData.getData();
                return ResponseData.buildErrorResponse(driverCheckDto.getStatus(), driverCheckDto.getRemark(), driverCheckDto);
            }
            //删除缓存
            redisCacheService.delete("driverRegisterCount" + mobile);
            return ResponseData.buildSuccessResponse(null);
        }
        registerCount++;
        redisCacheService.set("driverRegisterCount" + mobile, registerCount, 3L);
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "验证码错误");
    }

    @RequestMapping(value = {"/addRegister"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "注册接口", response = ResponseData.class)
    public ResponseData<Boolean> addRegister(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid", required = true) String appid,
            @ApiParam(name = "mobile", value = "司机手机号", required = true) @RequestParam(value = "mobile", required = true) String mobile,
            @ApiParam(name = "name", value = "姓名", required = true) @RequestParam(value = "name", required = true) String name,
            @ApiParam(name = "face", value = "头像", required = true) @RequestParam(value = "face", required = true) String face,
            @ApiParam(name = "idCard", value = "身份证号", required = true) @RequestParam(value = "idCard", required = true) String idCard,//身份证号idCard
            @ApiParam(name = "idCardFaceImg", value = "身份证正面照", required = true) @RequestParam(value = "idCardFaceImg", required = true) String idCardFaceImg,//身份证正面照
            @ApiParam(name = "idCardBackImg", value = "身份证背面照", required = true) @RequestParam(value = "idCardBackImg", required = true) String idCardBackImg,//身份证背面照
            @ApiParam(name = "fullDriverIdCardImg", value = "手持身份证照片", required = true) @RequestParam(value = "fullDriverIdCardImg", required = true) String fullDriverIdCardImg,//手持身份证照片
            @ApiParam(name = "licenseNum", value = "驾驶证号") @RequestParam(value = "licenseNum", required = false) String licenseNum,//驾驶证号
            @ApiParam(name = "getDriverLicenseDate", value = "驾驶证注册时间", required = true) @RequestParam(value = "getDriverLicenseDate", required = true) Long getDriverLicenseDate,
            @ApiParam(name = "drivingLicenceHomeImg", value = "驾驶证正面照片", required = true) @RequestParam(value = "drivingLicenceHomeImg", required = true) String drivingLicenceHomeImg,//驾驶证正面照片
            @ApiParam(name = "drivingLicenceSubImg", value = "驾驶证反面照片", required = true) @RequestParam(value = "drivingLicenceSubImg", required = true) String drivingLicenceSubImg,//驾驶证反面照片
            @ApiParam(name = "certificateNo", value = "网络预约出租车司机资格证号", required = false) @RequestParam(value = "certificateNo", required = false) String certificateNo,
            @ApiParam(name = "networkCarCertificationImg", value = "网络预约出租车司机资格证照片", required = false) @RequestParam(value = "networkCarCertificationImg", required = false) String networkCarCertificationImg,
            @ApiParam(name = "inviter", value = "邀请人手机号") @RequestParam(value = "inviter", required = false) String inviter, //邀请人手机号
            @ApiParam(name = "inviterType", value = "邀请人类型") @RequestParam(value = "inviterType", required = false) Integer inviterType, //邀请人类型
            @ApiParam(name = "type", value = "类型(2：专车、3：跨城拼车)") @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(name = "agentUuid", value = "代理uuid",required = false) @RequestParam(value = "agentUuid",required = false) String agentUuid,
            @ApiParam(name = "companyUuid", value = "公司",required = false) @RequestParam(value = "companyUuid",required = false) String companyUuid,
            @ApiParam(name = "haveCar", value = "是否带车0无车 1有车") @RequestParam(value = "haveCar") Integer haveCar,
            @ApiParam(name = "plateNum", value = "车牌") @RequestParam(value = "plateNum", required = false) String plateNum,
            @ApiParam(name = "ownerName", value = "车辆所有人") @RequestParam(value = "ownerName", required = false) String ownerName,
            @ApiParam(name = "ownerNameMobile", value = "车辆所有人电话") @RequestParam(value = "ownerNameMobile", required = false) String ownerNameMobile,
            @ApiParam(name = "brand", value = "车辆品牌") @RequestParam(value = "brand", required = false) String brand,
            @ApiParam(name = "model", value = "车辆型号") @RequestParam(value = "model", required = false) String model,
            @ApiParam(name = "carColor", value = "车身颜色") @RequestParam(value = "carColor", required = false) String carColor,
            @ApiParam(name = "carModelUuid", value = "所属车型") @RequestParam(value = "carModelUuid", required = false) String carModelUuid,
            @ApiParam(name = "seats", value = "核定载客位") @RequestParam(value = "seats", required = false) Integer seats,
            @ApiParam(name = "certificate", value = "网络预约出租车辆运输证号") @RequestParam(value = "certificate", required = false) String certificate,
            @ApiParam(name = "transLicenseImg", value = "网络约约出租车辆运输证照片") @RequestParam(value = "transLicenseImg", required = false) String transLicenseImg,
            @ApiParam(name = "compulsoryInsuranceImg", value = "交强险照片") @RequestParam(value = "compulsoryInsuranceImg", required = false) String compulsoryInsuranceImg,
            @ApiParam(name = "commercialInsuranceImg", value = "商业险照片") @RequestParam(value = "commercialInsuranceImg", required = false) String commercialInsuranceImg,
            @ApiParam(name = "carAngle45Img", value = "车身45°角照片") @RequestParam(value = "carAngle45Img", required = false) String carAngle45Img,
            @ApiParam(name = "drivingPic", value = "行驶证正面") @RequestParam(value = "drivingPic", required = false) String drivingPic,
            @ApiParam(name = "drivingPicBack", value = "行驶证反面") @RequestParam(value = "drivingPicBack", required = false) String drivingPicBack,
            @ApiParam(name = "provinceid", value = "行驶证反面") @RequestParam(value = "provinceid", required = false) Integer provinceid,
            @ApiParam(name = "cityid", value = "行驶证反面") @RequestParam(value = "cityid", required = false) Integer cityid
    ) {
        Map<String, Object> map = MapUtils.build();
        map.put("idCard", idCard);
        map.put("appid", appid);
        ResponseData<List<DriverDto>> validDriver = driverService.getValidDriver(map);
        if (validDriver.isSuccess() && !CollectionUtils.isEmpty(validDriver.getData())) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "身份证号已存在，请联系管理员");
        }

        //是否带车注册 0否 1是
        if (haveCar != null && haveCar == 1) {
            List<CarDto> carDtoList = carService.list(MapUtils.build("plateNum", plateNum)).getData();
            if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(carDtoList)) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "车牌号已被注册，请联系管理员");
            }
        }
        DriverCheckDto driverCheckDto = new DriverCheckDto();
        driverCheckDto.setName(name);
        driverCheckDto.setFace(face);
        driverCheckDto.setMobile(mobile);
        driverCheckDto.setIdCard(idCard);
        driverCheckDto.setLicenseNum(licenseNum);
        driverCheckDto.setIdCardFaceImg(idCardFaceImg);
        driverCheckDto.setIdCardBackImg(idCardBackImg);
        driverCheckDto.setFullDriverIdCardImg(fullDriverIdCardImg);
        driverCheckDto.setDrivingLicenceHomeImg(drivingLicenceHomeImg);
        driverCheckDto.setDrivingLicenceSubImg(drivingLicenceSubImg);
        driverCheckDto.setStatus(DriverConstant.DRIVER_CHECK_PEND);
        driverCheckDto.setAppid(appid);
        if(agentUuid == null || agentUuid.equals("")) {
            driverCheckDto.setAgentUuid("5f071b90b0514a099c11a2bfc535e917");
        } else {
            driverCheckDto.setAgentUuid(agentUuid);
        }
        if(companyUuid == null || companyUuid.equals("")) {
            driverCheckDto.setCompanyUuid("21ee7e1ae8eb449a83405e49cb3582a1");
        } else {
            driverCheckDto.setCompanyUuid(companyUuid);
        }
        driverCheckDto.setCreateOn(new Date());
        driverCheckDto.setCertificateNo(certificateNo);
        driverCheckDto.setNetworkCarCertificationImg(networkCarCertificationImg);
        driverCheckDto.setHaveCar(haveCar);
        driverCheckDto.setPlateNum(plateNum);
        driverCheckDto.setOwnerName(ownerName);
        driverCheckDto.setOwnerNameMobile(ownerNameMobile);
        driverCheckDto.setBrand(brand);
        driverCheckDto.setModel(model);
        driverCheckDto.setCarColor(carColor);
        driverCheckDto.setCarModelUuid(carModelUuid);
        driverCheckDto.setSeats(seats);
        driverCheckDto.setCertificate(certificate);
        driverCheckDto.setTransLicenseImg(transLicenseImg);
        driverCheckDto.setCompulsoryInsuranceImg(compulsoryInsuranceImg);
        driverCheckDto.setCommercialInsuranceImg(commercialInsuranceImg);
        driverCheckDto.setCarAngle45Img(carAngle45Img);
        driverCheckDto.setGetDriverLicenseDate(new Date(getDriverLicenseDate));
        driverCheckDto.setDrivingPic(drivingPic);
        driverCheckDto.setDrivingPicBack(drivingPicBack);
        driverCheckDto.setProvinceid(provinceid);
        driverCheckDto.setCityid(cityid);
        map.clear();
        map.put("mobile", mobile);
        map.put("appid", appid);
        map.put("type", type);
        DriverCheckDto oldCheckDto = driverCheckService.getLatest(map).getData();
        if (oldCheckDto != null && !oldCheckDto.getStatus().equals(DriverConstant.DRIVER_CHECK_NOT_PASS)) {
            //待审核或者已通过
            return ResponseData.buildSuccessResponse("已经注册了", null);
        }
        //新增
        driverCheckDto.setUuid(StringUtils.buildUUID());
        driverCheckDto.setBusinessType(type);
        driverCheckDto.setStatus(DriverConstant.DRIVER_CHECK_PEND);
        driverCheckService.add(driverCheckDto);
        // 如果有邀请人的话 则记录邀请关系
        if (StringUtils.isNotEmpty(inviter)) {
            //记录邀请关系
            MarketingInviteLogDto inviteLogDto = new MarketingInviteLogDto();
            inviteLogDto.setUuid(StringUtils.buildUUID());
            inviteLogDto.setInvitee(mobile);
            inviteLogDto.setInviter(inviter);
            inviteLogDto.setInviterType(inviterType);
            inviteLogDto.setInviteeType(2);
            inviteLogDto.setCreateOn(new Date());
            marketingInviteLogService.add(inviteLogDto);
        }
        return ResponseData.buildSuccessResponse("注册成功", Boolean.TRUE);

    }

    @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "司机申请上传图片", response = ResponseData.class)
    public ResponseData<String> adminDriUpload(@RequestParam MultipartFile file, @RequestParam String appid, @RequestParam String mobile) {
        String fileName = file.getOriginalFilename();
        String lastName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!lastName.equals("jpg") && !lastName.equals("png") && !lastName.equals("jpeg") && !lastName.equals("bmp")) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "图片格式不正确，请重新选择！");
        }
        ResponseData<String> responseData = FileUploadUtil.uploadImage(file, appid, mobile, "avatar");
        if (responseData.isSuccess()) {
            String face = (responseData.getData()).replaceAll("\\\\", "/");
            return ResponseData.buildSuccessResponse("上传成功", face);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "上传失败");

    }

    @RequestMapping(value = {"/uploadB64"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "司机申请上传图片", response = ResponseData.class)
    public ResponseData<String> adminDriUploadB64(@RequestBody Map<String, Object> map) {
        String imageFile = map.get("imageFile").toString();
        String appid = map.get("appid").toString();
        String mobile = map.get("mobile").toString();
        imageFile = imageFile.replaceAll("data:image/(.*);base64,", "");
        try {
            byte[] imageByte = Base64Utils.decode(imageFile);
            for (int i = 0; i < imageByte.length; ++i) {
                // 调整异常数据
                if (imageByte[i] < 0) {
                    imageByte[i] += 256;
                }
            }
            ResponseData<String> responseData = FileUploadUtil.uploadImage(imageByte, "123.jpg", appid, mobile, "avatar");
            if (responseData.isSuccess()) {
                String face = (responseData.getData()).replaceAll("\\\\", "/");
                return ResponseData.buildSuccessResponse("上传成功", face);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "上传失败");
    }


    @RequestMapping(value = "/listAgent", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取代理列表", response = ResponseData.class)
    public ResponseData<List<SysRegionalAgentDto>> listAgent(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
            @ApiParam(name = "businessType", value = "业务类型", required = true) @RequestParam(value = "businessType") String businessType) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("appid", appid);
        //开通的代理
        map.put("status", 1);
        map.put("businessType", businessType);
        return sysRegionalAgentService.findAgentByBusinessType(map);
    }


    @RequestMapping(value = "/listCompany", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "根据代理获取公司列表", response = ResponseData.class)
    public ResponseData<List<SysCompanyDto>> listCompanyByAgent(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
            @ApiParam(name = "agentUuid", value = "代理uuid", required = true) @RequestParam(value = "agentUuid") String agentUuid,
            @ApiParam(name = "businessType", value = "业务类型", required = true) @RequestParam(value = "businessType") String businessType) {
        Map<String, Object> map = new HashMap(5);
        map.put("appid", appid);
        map.put("regionalAgentUuid", agentUuid);
        map.put("status", 1);
        map.put("businessType", businessType);
        return sysCompanyService.findCompanyByBusinessType(map);
    }

    @RequestMapping(value = "/queryCarModel", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取车型", response = ResponseData.class)
    public ResponseData<List<Map<String, Object>>> queryCarModel(
            @ApiParam(name = "businessType", value = "业务类型", required = true) @RequestParam(value = "businessType") Integer businessType) {
        ResponseData<List<CarModelDto>> carModelRsd = carModelService.list(MapUtils.build("businessType", businessType));
        List<CarModelDto> carModelDtoList = carModelRsd.getData();
        if (CollectionUtils.isEmpty(carModelDtoList)) {
            return ResponseData.buildSuccessResponse(new ArrayList<>());
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (CarModelDto carModelDto : carModelDtoList) {
            Map<String, Object> map = new HashMap<>();
            map.put("carModelUuid", carModelDto.getUuid());
            map.put("carModelName", carModelDto.getModelName());
            resultList.add(map);
        }
        return ResponseData.buildSuccessResponse(resultList);
    }

}
